"""TypeScript相关的衍生配置处理"""

from typing import Dict, Any
from ...type.types import MySQLTypeInfo, MiaomaType
from ...type.converters import get_ts_type, MySQLToMiaomaTypeConverter
from ...type.type_info import MIAOMA_TYPE_INFO_MAP

def derive_ts_config(meta_info: Dict[str, Any]) -> Dict[str, Any]:
    """处理meta.json的TypeScript相关衍生配置

    处理字段级衍生配置:
    - columns.*.derived.ts.type: TypeScript类型
    - columns.*.derived.ts.mock_rule: Mock规则

    :param meta_info: meta.json格式的结构体
    :return: 更新后的结构体,可以继续传递给其他derived函数处理
    """
    # 遍历处理每个column
    for column_name, column_info in meta_info["columns"].items():
        try:
            # 从column_info中提取类型信息
            sql_type = column_info["sql"]["type"]
            type_info = MySQLTypeInfo(
                name=sql_type["name"].upper(),
                length=sql_type.get("length"),
                precision=sql_type.get("precision"),
                scale=sql_type.get("scale")
            )

            # 添加derived配置
            if "derived" not in column_info:
                column_info["derived"] = {}
            if "ts" not in column_info["derived"]:
                column_info["derived"]["ts"] = {}

            # 设置TypeScript类型
            ts_type = get_ts_type(type_info)
            column_info["derived"]["ts"]["type"] = ts_type

            # 设置Mock规则
            miaoma_type = MySQLToMiaomaTypeConverter.convert(
                mysql_type=type_info.name,
                length=type_info.length,
                precision=type_info.precision,
                scale=type_info.scale
            )
            mock_rule = MIAOMA_TYPE_INFO_MAP[miaoma_type].mock_rule

            # 如果是STRING类型且有length，使用具体的length
            if miaoma_type == MiaomaType.MIAOMA_BASE_STRING and type_info.length:
                mock_rule = f'@string({min(5, type_info.length)}, {type_info.length})'
            # 如果是DECIMAL/FLOAT类型且有precision和scale，使用具体的precision和scale
            elif miaoma_type in [MiaomaType.MIAOMA_BASE_DECIMAL, MiaomaType.MIAOMA_BASE_FLOAT] and type_info.precision and type_info.scale:
                mock_rule = f'@float(0, 100, {type_info.scale})'

            column_info["derived"]["ts"]["mock_rule"] = mock_rule

        except Exception as e:
            # 如果转换失败,使用默认映射
            if "derived" not in column_info:
                column_info["derived"] = {}
            if "ts" not in column_info["derived"]:
                column_info["derived"]["ts"] = {}

            sql_type = column_info["sql"]["type"]["name"].upper()
            ts_type = "number" if sql_type in ["BIGINT", "INT", "INTEGER", "TINYINT"] else "string"
            column_info["derived"]["ts"]["type"] = ts_type

            # 设置默认的Mock规则
            mock_rule = '@integer(0, 100)' if ts_type == 'number' else '@string(10)'
            column_info["derived"]["ts"]["mock_rule"] = mock_rule

    return meta_info